﻿using System.Web.Mvc;

namespace Portal
{
    using System.ComponentModel;
    using System.Text.RegularExpressions;
    using System.Web;

    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class MvcHtmlStringExtension
    {
        #region ForSearch

        /// <summary>
        /// 为当前表单元素添加搜索条件
        /// </summary>
        /// <param name="str"></param>
        /// <param name="method">搜索方法</param>

        /// <returns></returns>
        public static string ForSearch(this MvcHtmlString str, QueryMethod? method)
        {
            var wrapper = MvcHtmlWrapper.Create(str);
            string prefix = "";
            bool hasId = false;
            string orGroup = "";
            if (!method.HasValue) return wrapper.ToHtmlString();
            var html = wrapper.ToHtmlString();
            #region 如果是CheckBox，则去掉hidden

            if (html.Contains("type=\"checkbox\""))
            {
                var checkMatch = Regex.Match(html, "<input name=\"[^\"]+\" type=\"hidden\" [^>]+ />");
                if (checkMatch.Success)
                {
                    wrapper.Add(checkMatch.Groups[0].Value, string.Empty);
                }
            }

            #endregion

            #region 替换掉Name
            var match = Regex.Match(html, "name=\"(?<name>[^\"]+)\"");
            var strInsert = "";
            if (!string.IsNullOrEmpty(prefix))
            {
                strInsert += string.Format("({0})", prefix);
            }
            if (!string.IsNullOrEmpty(orGroup))
            {
                strInsert += string.Format("{{{0}}}", orGroup);
            }
            if (match.Success)
            {
                var tem = string.Format("name=\"[{1}]{2}{0}\"", match.Groups[1].Value, method, strInsert);
                wrapper.Add(match.Groups[0].Value, tem);

            }

            #endregion
            return wrapper.ToHtmlString();

        }

        #endregion
    }
}
